<script setup lang="ts">
import {
  copyActivityApi,
  getCategoryAllApi,
  getLastTimeApi,
} from "@/addon/htscrm/api";
import { t } from "@/lang";
import { dayjs, ElMessage, FormInstance, TabPaneName } from "element-plus";
import { cloneDeep } from "lodash-es";
import { ref } from "vue";

/** 表单实例 */
const formRef = ref<FormInstance>();
/** 表单数据 */
const formData = ref<{ data: ICopyItem[] }>({
  data: [],
});

/** 分类列表 */
const categoryList = ref<ICategoryItem[]>([]);
/** 默认选中的活动 */
const defaultSelection = ref<IActivityItem[]>([]);
/** 选中的分类 */
const categorySelection = ref<ICategoryItem[]>([]);
const active = ref(0);
const currentType = ref(1);
const title = ref("");
// const startTime = ref<number|null>(null)

/**
 * @description 初始化
 */
function init(selection: IActivityItem[], type: number, cate: ICategoryItem) {
  currentType.value = type;
  categorySelection.value = [];
  defaultSelection.value = selection || [];
  if (type == 1) {
    formData.value.data = [];
    getCategory();
  } else {
    getCateTime(cate);
  }
}

async function getCateTime(cate: any) {
  const res = await getLastTimeApi({ cate_ids: [cate.id] });
  const data = res.data[0];
  formData.value.data = [];
}

/**
 * @description 提交保存
 */
function submit() {
  return new Promise(async (resolve, reject) => {
    if (currentType.value == 1) {
      if (categorySelection.value.length) {
        const params = cloneDeep(formData.value);
        params.data.forEach((item) => {
          console.log("item.activitys", item.activitys);
          item.activitys = item.activitys.map((val) => {
            return {
              ...val,
              play_date: val.play_date.join(" 到 "),
              huifang_date: val.huifang_date.join(" 到 "),
              online_time: val.online_time
                ? parseInt(String(val.online_time / 1000))
                : null,
              offline_time: val.offline_time
                ? parseInt(String(val.offline_time / 1000))
                : null,
            };
          }) as any[];
        });
        if (!params.data.length) {
          ElMessage.error(t("请点击添加分类!"));
          return;
        }
        const res0 = await copyActivityApi(currentType.value, params);
        if (res0.code === 1) {
          ElMessage.success(t("save.success"));
          resolve(true);
        } else {
          ElMessage.error(res0.msg);
          reject(new Error(t("form.validateError")));
        }
      } else {
        ElMessage.error(t("请选择活动分类!"));
        reject(new Error(t("form.validateError")));
      }
    } else {
      formRef.value?.validate(async (valid) => {
        if (valid) {
          const params = cloneDeep(formData.value);
          params.data.forEach((item) => {
            console.log("item.activitys", item.activitys);
            item.activitys = item.activitys.map((val) => {
              return {
                ...val,
                play_date: val.play_date.join(" 到 "),
                huifang_date: val.huifang_date.join(" 到 "),
                online_time: val.online_time
                  ? parseInt(String(val.online_time / 1000))
                  : null,
                offline_time: val.offline_time
                  ? parseInt(String(val.offline_time / 1000))
                  : null,
              };
            }) as any[];
          });

          await copyActivityApi(currentType.value, params);

          ElMessage.success(t("save.success"));
          resolve(true);
        } else {
          reject(new Error(t("form.validateError")));
        }
      });
    }
  });
}

/**
 * 获取分类列表
 */
async function getCategory() {
  const res = await getCategoryAllApi();
  categoryList.value = res.data;
}

/**
 * 选中分类
 */
async function handleAddCategory() {
  const cateIds: number[] = categorySelection.value.map((item) =>
    Number(item.id)
  );
  const res = await getLastTimeApi({ cate_ids: cateIds });
  formData.value.data = categorySelection.value.map((item) => {
    const cate = res.data.find((val) => val.cate_id == item.id);
    // 如果分类时间存在
    return {
      cate_id: item.id,
      title: item.title,
      activitys: cloneDeep(defaultSelection.value).map((val,index) => {
        return format(val, cate, index + 1);
      }),
    };
  });
}
function handleAdd() {
  formData.value.data.push({
    cate_id: 0,
    title: title.value,
    activitys: cloneDeep(defaultSelection.value).map((val) => {
      return format(val);
    }),
  });
  active.value = formData.value.data.length - 1;
  title.value = '';
}

function format(val: any, cate?: any, index?: number) {
  console.log("val", val);
  console.log("cate", cate);
  const playDate = String(val.play_date) || '';
  const huifangDate = cate?.huifang_date || String(val.huifang_date)
  const offlineTime = cate?.offline_time || val.offline_time;
  const onlineTime = cate?.online_time || val.online_time;
  const result = {
    id: val.id,
    title: val.title,
    status: val.status,
    play_date: playDate ? playDate.split(" 到 ") : [], //playDate ? playDate.split(" 到 ") : 
    huifang_date: huifangDate ? huifangDate.split(" 到 ") : [],
    offline_time: offlineTime ? new Date(offlineTime).getTime() : null,
    online_time: onlineTime ? new Date(onlineTime).getTime() : null,
  };
  handleAddDate(result, "play_date", index);
  handleAddDate(result, "huifang_date", index);
  handleAddDate(result, "offline_time", index);
  handleAddDate(result, "online_time", index);

  return result;
}

/**
 * 修改单个活动的时间
 * @param row
 * @param type
 */
function handleAddDate(
  row: ICopyItem["activitys"][0],
  type: keyof ICopyItem["activitys"][0],
  index: number = 1
) {
  console.log(row[type]);

  switch (type) {
    case "play_date":
    case "huifang_date":
      if (row[type].length == 0) return;
      row[type] = [
        dayjs((dayjs(row[type][0]).unix() + (24 * 60 * 60 * index)) * 1000).format(
          "YYYY-MM-DD HH:mm:ss"
        ),
        dayjs((dayjs(row[type][1]).unix() + (24 * 60 * 60 * index)) * 1000).format(
          "YYYY-MM-DD HH:mm:ss"
        ),
      ];
      break;
    case "offline_time":
      if (!row[type]) return;
      row[type] =
        dayjs((dayjs(row[type]).unix() + (24 * 60 * 60 * index)) * 1000).unix() * 1000;
      console.log("offline_time", row[type]);
      break;
    case "online_time":
      if (!row[type]) return;
      row[type] =
        dayjs((dayjs(row[type]).unix() + (24 * 60 * 60 * index)) * 1000).unix() * 1000;
      console.log("online_time", row[type]);
      break;

    default:
      break;
  }
}

function handleAddAllDate(type: keyof ICopyItem["activitys"][0]) {
  formData.value.data[active.value].activitys.forEach((item) => {
    handleAddDate(item, type);
  });
}

function handleTabsEdit(targetName: number, action: "remove" | "add") {
  if (action === "remove") {
    formData.value.data.splice(targetName, 1);
    active.value = formData.value.data.length - 1
  }
}

defineExpose({
  init,
  submit,
});
</script>

<template>
  <el-form-item
    label="活动分类"
    prop="categorySelection">
    <el-row v-if="currentType == 1">
      <el-select
        class="max-w-[800px]"
        v-model="categorySelection"
        value-key="id"
        multiple
        placeholder="请选择活动分类"
        filterable>
        <el-option
          v-for="item in categoryList"
          :key="item.id"
          :label="item.title"
          :value="item"></el-option>
      </el-select>
      <el-button
        v-if="categorySelection.length"
        class="ml-[15px]"
        type="primary"
        @click="handleAddCategory"
        >{{ formData.data.length ? "更新分类" : "添加分类" }}</el-button
      >
    </el-row>
    <el-row v-if="currentType == 2">
      <el-input
        class="max-w-[300px]"
        v-model.trim="title"
        placeholder="请输入分类名称"></el-input>
      <!-- <el-date-picker
        class="ml-[15px] max-w-[300px]"
        v-model="startTime"
        type="datetime"
        :clearable="false"
        value-format="x"
        placeholder="请选择时间"></el-date-picker> -->
      <el-button
        class="ml-[15px]"
        type="primary"
        @click="handleAdd"
        >添加分类</el-button
      >
    </el-row>
  </el-form-item>
  <el-form
    ref="formRef"
    :model="formData"
    label-width="80px">
    <el-tabs
      v-if="formData.data.length"
      class="mt-[15px]"
      v-model="active"
      type="card"
      :editable="formData.data.length > 1"
      @edit="handleTabsEdit">
      <el-tab-pane
        v-for="(item, index) in formData.data"
        :key="index"
        :label="item.title"
        :name="index">
        <el-table :data="item.activitys">
          <el-table-column
            label="活动名称"
            width="200">
            <template #default="scope">
              <el-input
                v-model="scope.row.title"
                placeholder="请输入活动名称"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="直播时间"
            min-width="240">
            <template #header>
              <div class="flex items-center">
                <span>直播时间</span>
                <el-button
                  type="primary"
                  text
                  @click="handleAddAllDate('play_date')"
                  ><el-icon><Plus /></el-icon
                ></el-button>
              </div>
            </template>
            <template #default="scope">
              <div class="flex">
                <el-date-picker
                  v-model="scope.row.play_date"
                  type="datetimerange"
                  :clearable="false"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"></el-date-picker>
                <el-button
                  :disabled="scope.row.play_date.length == 0"
                  type="primary"
                  text
                  @click="handleAddDate(scope.row, 'play_date')"
                  ><el-icon><Plus /></el-icon
                ></el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="回放时间"
            min-width="240">
            <template #header>
              <div class="flex items-center">
                <span>回放时间</span>
                <el-button
                  type="primary"
                  text
                  @click="handleAddAllDate('huifang_date')"
                  ><el-icon><Plus /></el-icon
                ></el-button>
              </div>
            </template>
            <template #default="scope">
              <div class="flex">
                <el-date-picker
                  v-model="scope.row.huifang_date"
                  type="datetimerange"
                  :clearable="false"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"></el-date-picker>
                <el-button
                  :disabled="scope.row.huifang_date.length == 0"
                  type="primary"
                  text
                  @click="handleAddDate(scope.row, 'huifang_date')"
                  ><el-icon><Plus /></el-icon
                ></el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="状态"
            width="80">
            <template #default="scope">
              <el-switch
                :active-value="1"
                :inactive-value="0"
                v-model="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column
            label="自动上线时间"
            width="200">
            <template #header>
              <div class="flex items-center">
                <span>自动上线时间</span>
                <el-button
                  type="primary"
                  text
                  @click="handleAddAllDate('online_time')"
                  ><el-icon><Plus /></el-icon
                ></el-button>
              </div>
            </template>
            <template #default="scope">
              <div class="flex">
                <el-date-picker
                  v-model="scope.row.online_time"
                  type="datetime"
                  :clearable="true"
                  value-format="x"
                  placeholder="请选择时间"></el-date-picker>
                <el-button
                  :disabled="!scope.row.online_time"
                  type="primary"
                  text
                  @click="handleAddDate(scope.row, 'online_time')"
                  ><el-icon><Plus /></el-icon
                ></el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="自动下线时间"
            width="200">
            <template #header>
              <div class="flex items-center">
                <span>自动下线时间</span>
                <el-button
                  type="primary"
                  text
                  @click="handleAddAllDate('offline_time')"
                  ><el-icon><Plus /></el-icon
                ></el-button>
              </div>
            </template>
            <template #default="scope">
              <div class="flex">
                <el-date-picker
                  v-model="scope.row.offline_time"
                  type="datetime"
                  :clearable="true"
                  value-format="x"
                  placeholder="请选择时间"></el-date-picker>
                <el-button
                  :disabled="!scope.row.offline_time"
                  type="primary"
                  text
                  @click="handleAddDate(scope.row, 'offline_time')"
                  ><el-icon><Plus /></el-icon
                ></el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
  </el-form>
</template>

<style lang="scss" scoped>
:deep(.el-date-editor) {
  width: 100%;
}

.el-button.is-text {
  padding: 5px 10px;
}
</style>
